from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import ElementClickInterceptedException, ElementNotInteractableException, \
    StaleElementReferenceException

class BasePage(object):
    def __init__(self,driver,url):
        self.driver = driver
        if url is not None:
            self.driver.get(url)

    def find_element(self, locator):
        return Element(
            WebDriverWait(self.driver, 10).until(
                ec.presence_of_element_located(locator)), self.driver
        )

    def find_elements(self, locator):
        web_elements= WebDriverWait(self.driver, 10).until(
            ec.presence_of_all_elements_located(locator))
        return [Element(item,self.driver) for item in web_elements ]


class Element(object):
    def __init__(self, _element, driver):
        self.driver = driver
        self.element = _element

    def click(self):
        ## 忽略异常
        exception_tuples=(ElementClickInterceptedException,ElementNotInteractableException,StaleElementReferenceException)

        WebDriverWait(self.driver, 10,exception_tuples).until(
            lambda d:not self.element.click()
        )
    def send_keys(self, keys):
        self.element.send_keys(keys)

    def text(self,until_not_null=False):
        if not until_not_null:
            return self.element.text
        else:
            wat=WebDriverWait(self.driver, 10)
            def wait_until_not_null(element):
                def _method(m):
                    return self.element.text
                return _method
            return wat.until(wait_until_not_null(self))


